<template>
  <div class="budgetingPage">
    <common-title title-name="资金预算编制">
      <template #rightCnBox>
        <div style="width: 90%" class="d-flex j-end">
          <el-button
            size="small"
            class="button_view m-l10"
            style="margin-right: -25px"
            @click="importFile"
            >批量导入</el-button
          >
        </div>
      </template>
    </common-title>
    <el-card class="" shadow="never">
      <el-form label-width="150px" ref="formRef" :model="form" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="编制部门" prop="departmentId">
              <el-select v-model="form.departmentId" clearable>
                <el-option
                  v-for="(item, index) in departmentList"
                  :key="index"
                  :label="item.deptName"
                  :value="item.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年度" prop="year" label-width="130px">
              <el-date-picker
                class="m-l10"
                clearable
                v-model="form.year"
                value-format="YYYY"
                size="large"
                type="year"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="季度" prop="quarter">
              <el-select
                v-model="form.quarter"
                @change="quarterChange"
                clearable
              >
                <el-option label="第一季度" value="1"></el-option>
                <el-option label="第二季度" value="2"></el-option>
                <el-option label="第三季度" value="3"></el-option>
                <el-option label="第四季度" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!--                <el-col :span="8" class="d-flex j-center">
                              <el-form-item label="资金预算性质" clearable prop="temp">
                                  <el-cascader v-model="form.temp" :props="props" />
                              </el-form-item>
                          </el-col>-->
          <el-col :span="8">
            <el-form-item label="计划类型" clearable prop="planType">
              <el-select v-model="form.planType" clearable>
                <el-option label="计划内" value="1"></el-option>
                <el-option label="计划外" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务单元" clearable prop="businessUnitId">
              <el-select v-model="form.businessUnitId" clearable>
                <el-option
                  v-for="(item, index) in businessUnitList"
                  :key="index"
                  :label="item.businessUnitName"
                  :value="item.businessUnitId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div class="fund-details-box m-t30 d-flex j-sb">
      <span
        >资金计划项目明细(<span style="color: red"
          >备注：原则上资金计划填报至”项目子集”；按业务所需可填报至下级项目（支付时按项目集总额支配）</span
        >)</span
      >
      <div class="buttons-box">
        <el-button class="button_view" size="small" @click="addHandle"
          >添加</el-button
        >
        <el-button class="button_view" size="small" @click="reduceHandle"
          >删除</el-button
        >
        <el-button class="button_view" size="small" @click="copyHandle"
          >复制</el-button
        >
      </div>
    </div>

    <el-card class="m-t10" shadow="never">
      <el-form label-width="0px" ref="tableFormRef" :model="form">
        <el-table
          ref="tableRef"
          :data="form.list"
          :height="400"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column
            type="index"
            label="序号"
            align="center"
            min-width="50"
          >
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="月度" prop="monthly" min-width="80">
            <template #default="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.monthly'"
                :rules="rules.monthly"
              >
                <el-select clearable v-model="scope.row.monthly">
                  <el-option
                    v-for="item in monthList[form.quarter]"
                    :key="item"
                    :label="item + `月`"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="项目集" prop="projectSetId" min-width="100">
            <template #default="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.projectSetId'"
                :rules="rules.projectSetId"
              >
                <el-select
                  filterable
                  v-model="scope.row.projectSetId"
                  clearable
                  @change="
                    getSubProjectSet(
                      scope.row.projectSetId,
                      scope.$index,
                      $event
                    )
                  "
                >
                  <el-option
                    v-for="(item, index) in projectList"
                    :key="index"
                    :label="item.projectBelongAndSetName"
                    :value="item.projectSetId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="项目子集"
            prop="mainProjectId"
            min-width="100"
          >
            <template #default="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.mainProjectId'"
                :rules="rules.mainProjectId"
              >
                <el-select
                  filterable
                  v-model="scope.row.mainProjectId"
                  clearable
                  @change="
                    subProjectSetChange(
                      scope.row.mainProjectId,
                      scope.$index,
                      $event
                    )
                  "
                >
                  <el-option
                    v-for="(item, index) in form.list[scope.$index]
                      .subProjectSetList"
                    :key="index"
                    :label="item.projectSetName"
                    :value="item.projectSetId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="资金预算性质" prop="temp" min-width="120">
            <template #default="scope">
              <el-form-item
                clearable
                :prop="'list.' + scope.$index + '.temp'"
                :rules="rules.temp"
              >
                <el-cascader
                  clearable
                  v-model="scope.row.temp"
                  :props="props"
                  @change="tempChange($event, scope.row, scope.$index)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="资金预算科目"
            prop="subjectId"
            min-width="120"
          >
            <template #default="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.subjectId'"
                :rules="rules.subjectId"
              >
                <!-- <el-select v-model="scope.row.subjectId" clearable>
                                                  <el-option v-for="(item,index) in budgetSubjectList" :key="index" :label="item.subjectName" :value="item.subjectId"></el-option>
                                              </el-select> -->
                <el-cascader
                  clearable
                  :disabled="scope.row.temp === ''"
                  :placeholder="
                    scope.row.temp === '' ? '请先选择资金预算性质' : '请选择'
                  "
                  v-model="scope.row.subjectId"
                  :props="props2"
                  :options="scope.row.options"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="类型">
            <template #default="scope">
              <el-form-item>
                <span>{{ { "1": "流入", "2": "流出" }[scope.row.type] }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="资金预算金额"
            prop="budgetAmount"
            min-width="80"
          >
            <template #default="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.budgetAmount'"
                :rules="rules.budgetAmount"
              >
                <el-input
                  clearable
                  v-model="scope.row.budgetAmount"
                  @input="
                    scope.row.budgetAmount = limitInputNum(
                      scope.row.budgetAmount,
                      13,
                      3,
                      true
                    )
                  "
                  placeholder="请输入资金预算金额"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="50">
            <template #default="scope">
              <el-form-item :prop="'list.' + scope.$index + '.remarks'">
                <el-input
                  clearable
                  v-model="scope.row.remarks"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-card>
    <div class="buttons-box m-t20 d-flex a-center j-center">
      <el-button @click="onSave()" :loading="loading" class="button_view"
        >保存</el-button
      >
    </div>
  </div>
  <input id="input" style="width: 0; height: 0; opacity: 0" />
  <importDialog ref="importDialogRef" />
</template>

<script setup>
import {
  ElCard,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
  ElMessage,
  ElDatePicker,
  ElCascader,
  ElTable,
  ElTableColumn,
} from "element-plus";
import CommonTitle from "@/components/CommonTitle.vue";
import { onMounted, reactive, ref, watch, computed } from "vue";
import { fundManagementApi, otherApi } from "@/api/businessFinance";
import { limitInputNum, localGet, resetForm } from "@/common/utils/GlobalUtils";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import ImportDialog from "./components/importDialog";
import { Bottom, Position, Right } from "@element-plus/icons-vue";

const currentIndex = ref("");
const page = reactive({
  total: 0,
  current: 1,
  size: 10,
});

const monthList = ref([[], [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]);

const list = ref([]);
const handleSelectionChange = (e) => {
  list.value = e;
};

const departmentList = ref([]);
const getDepartmentVo = () => {
  fundManagementApi
    .getDepartmentVo({ departmentId: localGet("DepartmentId") })
    .then((res) => {
      departmentList.value = res.data;
      departmentList.value.forEach((item) => {
        if (item.deptId === localGet("DepartmentId")) {
          form.departmentId = localGet("DepartmentId");
        }
      });
    });
};

let form = reactive({
  departmentId: "",
  year: "",
  quarter: "",
  mainProjectId: "",
  moneyType: "",
  planType: "",
  temp: "",
  list: [],
  businessUnitId: "",
});

const rules = reactive({
  departmentId: [
    { required: true, message: "编制部门,不能为空!", trigger: "change" },
  ],
  year: [{ required: true, message: "年度,不能为空!", trigger: "blur" }],
  quarter: [{ required: true, message: "季度,不能为空!", trigger: "change" }],
  mainProjectId: [
    { required: true, message: "项目子集不能为空!", trigger: "change" },
  ],
  temp: [
    { required: true, message: "资金预算性质不能为空!", trigger: "change" },
  ],
  monthly: [{ required: true, message: "月度不能为空!", trigger: "change" }],
  /*  subprojectId: [
        { required: true, message: "相关项目,不能为空!", trigger: "change" },
      ],
      contractId: [
        { required: true, message: "相关合同,不能为空!", trigger: "change" },
      ],*/
  subjectId: [
    { required: true, message: "资金预算科目不能为空!", trigger: "change" },
  ],
  budgetAmount: [
    { required: true, message: "资金预算金额不能为空!", trigger: "blur" },
  ],
  planType: [
    { required: true, message: "计划类型不能为空!", trigger: "change" },
  ],
  businessUnitId: [
    { required: true, message: "业务单元不能为空!", trigger: "change" },
  ],
});

/**
 *
 * @param e
 */
const quarterChange = (e) => {
  if (form.list.length && form.list[form.list.length - 1].monthly) {
    form.list[form.list.length - 1].monthly = "";
  }
};

const getUuid = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

const formRef = ref(null);
const addHandle = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      form.list.push({
        uuid: getUuid(),
        monthly: "",
        mainProjectId: "",
        subprojectId: "",
        contractId: "",
        temp: "",
        subjectId: "",
        budgetAmount: "",
        remarks: "",
        options: [],
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const reduceHandle = () => {
  if (list.value.length === 0) {
    ElMessage.warning("请选择需要操作的行!");
    return;
  }
  list.value.forEach((item) => {
    form.list.forEach((val, index) => {
      if (item.uuid === val.uuid) {
        form.list.splice(index, 1);
      }
    });
  });
};

const tableRef = ref(null);
const copyHandle = () => {
  if (list.value.length === 0) {
    ElMessage.warning("请选择需要操作的行!");
    return;
  }
  let newList = JSON.parse(JSON.stringify(list.value));
  for (let item of newList) {
    item.uuid = getUuid();
  }
  form.list.push(...newList);

  // list.value = [];
  // tableRef.value.clearSelection();
};

const projectList = ref([]);
const getProjectSets = () => {
  fundManagementApi.getProjectSets().then((res) => {
    projectList.value = res.data;
  });
};

/**
 * 获取部门可使用的项目集树状结构，不分页
 */
const getDepartmentProjectSetTree = () => {
  fundManagementApi.getDepartmentProjectSetTree().then((res) => {
    projectList.value = res.data;
  });
};

/**
 * 查询项目下的合同
 *
 */
const contractList = ref([]);
const getListByProjectId = (projectId, i) => {
  otherApi.getContractList(projectId).then((res) => {
    // contractList.value = res.data;
    form.list[i].contractList = res.data;
  });
};

const budgetSubjectList = ref([]);
const options = ref([]);
const getBudgetSubjectList = (param, callback) => {
  return fundManagementApi.getBudgetSubjectList(param).then((res) => {
    budgetSubjectList.value = res.data;
    if (callback) callback(res);
  });
};

const tempNode = ref([]);

const props = {
  lazy: true,
  async lazyLoad(node, resolve) {
    console.log("nodex1", node);
    const { level } = node;
    try {
      if (level === 0) {
        await getBudgetSubjectList({
          subjectId: "",
          subjectType: "1",
        });
        let nodes = [];
        budgetSubjectList.value.forEach((item) => {
          nodes.push({
            value: item.subjectId,
            label: item.subjectName,
            leaf: level >= 1,
          });
        });
        tempNode.value.push(...nodes);
        resolve(nodes);
      }
      if (level > 0 && level === 2) {
        tempNode.value = [];
        resolve([]);
      }
      if (level > 0 && level < 2) {
        await getBudgetSubjectList({
          subjectId: node.value,
          subjectType: "1",
        });
        let nodes = [];
        budgetSubjectList.value.forEach((item) => {
          nodes.push({
            value: item.subjectId,
            label: item.subjectName,
            leaf: level >= 1,
          });
        });
        tempNode.value.push(...nodes);
        resolve(nodes);
      }
    } catch (e) {
      let nodes = [];
      resolve(nodes);
    }
  },
};

const props2 = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level } = node;
    try {
      if (level === 0) {
        const res = await fundManagementApi.getBudgetSubjectList({
          subjectId:
            form.list[currentIndex.value]?.temp === undefined
              ? ""
              : form.list[currentIndex.value].temp[
                  form.list[currentIndex.value].temp.length - 1
                ],
          subjectType: "1",
        });
        let nodes = [];
        res.data.forEach((item) => {
          nodes.push({
            value: item.subjectId,
            label: item.subjectName,
            leaf: level >= 2,
          });
        });
        resolve(nodes);
      }
      if (level > 0 && level === 3) {
        resolve([]);
      }
      if (level > 0 && level < 3) {
        const res = await fundManagementApi.getBudgetSubjectList({
          subjectId: node.value,
          subjectType: "1",
        });
        let nodes = [];
        res.data.forEach((item) => {
          nodes.push({
            value: item.subjectId,
            label: item.subjectName,
            leaf: level >= 2,
          });
        });
        resolve(nodes);
      }
    } catch (e) {
      let nodes = [];
      resolve(nodes);
    }
  },
};

const getProjects = (projectSetId, i) => {
  fundManagementApi.getProjects(projectSetId).then((res) => {
    // relatedProjects.value = res.data;
    form.list[i].relatedProjects = res.data;
  });
};

/**
 * 根据项目集id获取子集列表
 * @param projectSetId
 * @param i
 * @param e
 */
const getSubProjectSet = (projectSetId, i, e) => {
  if (!e) {
    form.list[i].subProjectSetList = [];
    form.list[i].mainProjectId = "";
  }
  if (e) {
    form.list[i].mainProjectId = "";
    fundManagementApi
      .getProjectSetChildList({ projectSetId: projectSetId })
      .then((res) => {
        form.list[i].subProjectSetList = res.data;
      });
  }
};

/**
 * 子集选择时触发
 * @param mainProjectId
 * @param i
 * @param e
 */
const subProjectSetChange = (mainProjectId, i, e) => {};

/**
 * 获取项目详情
 */
const projectList2 = ref([]);
const getProjectDetailInfo = () => {
  fundManagementApi.getProjectDetailInfo().then((res) => {
    if (res.code === "200") {
      projectList2.value = res.data;
    }
  });
};

const router = useRouter();
const createBudget = (param, callback, err_callback) => {
  fundManagementApi.createBudget(param).then((res) => {
    if (res.code === "200") {
      if (callback) callback(res);
    } else {
      if (err_callback) err_callback(res);
    }
  });
};

const loading = ref(false);
const tableFormRef = ref(null);
const onSave = async () => {
  await formRef.value.validate();
  if (form.list.length === 0) {
    ElMessage.warning("请添加资金计划项目明细");
    return;
  }
  await tableFormRef.value.validate();
  let parmas = [];
  form.list.forEach((item) => {
    let obj = {
      ...form,
      ...item,
    };
    if (obj.subjectId instanceof Array) {
      obj.subjectId = obj.subjectId[obj.subjectId.length - 1];
    }
    if (obj.list !== undefined) {
      delete obj.list;
    }
    if (obj.temp !== undefined) {
      delete obj.temp;
    }
    if (obj.contractList !== undefined) {
      delete obj.contractList;
    }
    if (obj.relatedProjects !== undefined) {
      delete obj.relatedProjects;
    }
    parmas.push(obj);
  });

  loading.value = true;
  createBudget(
    parmas,
    () => {
      loading.value = false;
      ElMessage.success("操作成功!");
      resetForm(form);
      formRef.value.resetFields();
      /* router.push({
               path: `/businessFinance/fundManagement/fundBudgetManagement/budgetLedger2`,
             });*/

      router.push({
        path: `/businessFinance/fundManagement/fundBudgetManagement/budgetLedger6`,
      });
    },
    () => {
      loading.value = false;
      ElMessage.error("操作失败!");
    }
  );
};

/**
 * 项目选择器下拉选择时触发
 *
 */
const projectChange = (e, i, row) => {
  if (e) {
    form.list[i].mainProjectId = projectList2.value.filter((item) => {
      if (item.projectId === row.subprojectId) {
        return item;
      }
    })[0].projectSetId;
    getListByProjectId(e, i);
  } else {
    form.list[i].mainProjectId = "";
  }
};

/**
 * 获取业务单元
 */
const businessUnitList = ref([]);
const getFundBudgetBusinessUnitAll = () => {
  fundManagementApi.getFundBudgetBusinessUnitAll().then((res) => {
    if (res.code === "200") {
      businessUnitList.value = res.data;
    }
  });
};

/**
 * 资金预算性质
 */
const tempChange = (e, row, index) => {
  //  筛选出资金预算类型
  form.list[index].type = 0;
  if (e) {
    let id = e[e.length - 1];
    let label = "";
    console.log("tempNode.value", tempNode.value);
    let list = tempNode.value.filter((item) => {
      if (id === item.value) {
        return item;
      }
    });
    console.log("list", list);
    if (list.length) {
      label = list[0].label;
    }
    if (label.indexOf("流入") !== -1) {
      form.list[index].type = 1;
    }
    if (label.indexOf("流出") !== -1) {
      form.list[index].type = 2;
    }
  }

  currentIndex.value = index;
  let arr = row.temp;
  row.options = [];
  row.subjectId = "";
  getBudgetSubjectList(
    {
      subjectId: arr[arr.length - 1],
      subjectType: "1",
    },
    (res) => {
      res.data.forEach((item) => {
        row.options.push({
          label: item.subjectName,
          value: item.subjectId,
        });
      });
    }
  );
};

/*watch(()=>form.mainProjectId,(newVal)=>{
    if(newVal){
        getProjects(newVal);
    }
});*/

/*watch(()=>form.temp,(newVal)=>{
    if(typeof newVal === 'object' && newVal.length!==0){
        getBudgetSubjectList({
            subjectId:newVal[newVal.length-1],
            subjectType:'1'
        },(res)=>{
                res.data.forEach(item=>{
                    options.value.push({
                        label:item.subjectName,
                        value:item.subjectId
                    });
                });
        });
    }
});*/

let store = useStore();
let formObj = computed(() => {
  let value = store.state.menu.saveData.find((item) => {
    return item.name === "budgeting";
  });
  return value;
});

const state = reactive({
  projectSetsList: [],
});

/**
 * 根据部门获取项目集
 */
const getDepartmentProjectSet = () => {
  let params = {
    departmentId: localGet("DepartmentId"),
  };
  fundManagementApi.getDepartmentProjectSet(params).then((res) => {
    const { code, data, msg } = res;
    if (code === "200") {
      state.projectSetsList = data;
    }
  });
};

onMounted(() => {
  getProjectDetailInfo();
  getDepartmentVo();
  // getProjectSets();
  // getDepartmentProjectSet();
  getDepartmentProjectSetTree();
  getFundBudgetBusinessUnitAll();
  if (formObj && formObj.value) {
    form = Object.assign(form, formObj.value.value);
  }
});

let path = "/businessFinance/fundManagement/fundBudgetManagement/budgeting"; // 预算编制路由
watch(
  () => router.currentRoute.value.path,
  (val) => {
    // 编辑状态缓存控制
    let i = store.state.menu.breadcrumbItemsArr.findIndex((item) => {
      return item.path === path;
    });
    if (i > -1) {
      store.commit("SAVE_STATE", {
        name: "budgeting",
        value: form,
      });
    } else {
      store.commit("DELETE_STATE");
    }
  }
);

watch(
  () => form,
  (value) => {
    if (value) {
      store.commit("set_budgetingForm", form);
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  if (
    JSON.stringify(store.state.collaborativeApproval.budgetingForm) !== "{}"
  ) {
    for (let key in store.state.collaborativeApproval.budgetingForm) {
      form[key] = store.state.collaborativeApproval.budgetingForm[key];
    }
  }
});

let importDialogRef = ref(null);
let importFile = () => {
  importDialogRef.value.visible = true;
};
</script>

<style lang="scss" scoped>
.budgetingPage {
  .fund-details-box {
    .buttons-box {
      display: flex;
      align-items: center;

      .icon {
        cursor: pointer;
        width: 28px;
        height: 28px;
      }
    }
  }
}
</style>
